package guitar

import (
	"context"
	"fmt"
	"net/http"

	"go-weixin/app/guitar/api/internal/svc"
	"go-weixin/app/guitar/api/internal/types"

	"github.com/xuri/excelize/v2"
	"github.com/zeromicro/go-zero/core/logx"
)

type GuitarExcelLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGuitarExcelLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GuitarExcelLogic {
	return &GuitarExcelLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GuitarExcelLogic) GuitarExcel(req *types.GuitarExcelReq, w http.ResponseWriter) (resp *types.GuitarExcelResp, err error) {
	f := excelize.NewFile()
	type BodyRow struct {
		name     string
		age      int64
		email    string
		password string
	}
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	headersRow := []string{"姓名", "年龄", "邮箱", "密码"}
	var bodyRows []BodyRow
	for i := 0; i < 10; i++ {
		bodyRows = append(bodyRows, BodyRow{
			name:     fmt.Sprintf("name_%d", i),
			age:      int64(i),
			email:    fmt.Sprintf("email_%d", i),
			password: fmt.Sprintf("password_%d", i),
		})
	}

	// 设置第一行
	cell, err := excelize.CoordinatesToCellName(1, 1)
	if err != nil {
		return nil, err
	}
	f.SetSheetRow("Sheet1", cell, &headersRow)

	// 设置主数据
	for idx, row := range bodyRows {
		cell, err := excelize.CoordinatesToCellName(1, idx+2)
		if err != nil {
			return nil, err
		}
		f.SetSheetRow("Sheet1", cell, &[]interface{}{row.name, row.age, row.email, row.password})
	}

	// 设置活动的工作蒲
	f.SetCellValue("Sheet1", "B2", 100)
	f.Write(w)
	return
}
